package com.business.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.business.commons.result.TokenResult;
import com.business.commons.utils.JsonUtils;
import com.business.service.system.TokenService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * h5 token 拦截器
 * 
 * @author limt
 * 
 */
public class H5TokenInterceptor extends HandlerInterceptorAdapter {

	private static final Logger logger = LoggerFactory.getLogger(H5TokenInterceptor.class);
	
	@Autowired
	private TokenService tokenService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (handler instanceof HandlerMethod) {
			HandlerMethod handlerMethod = (HandlerMethod) handler;
			Method method = handlerMethod.getMethod();
			H5TokenRequired annotation = method.getAnnotation(H5TokenRequired.class);
			if (annotation != null) {
				boolean needToken = annotation.needToken();
				if (needToken) {
					return handleToken(request, response, handler);
				}
			}
		}
		return true;
	}

	protected boolean handleToken(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 获取token
		String token = request.getParameter("token");
		// 是否过期 非0，没有过期 0，过期
		boolean tokens = tokenService.checkTokenDecrypt(token);
		if (tokens) {
			logger.info("未通过验证...");
			if (isRedirectMethod(request, response, (HandlerMethod) handler)) {
				response.sendRedirect(request.getContextPath() + "/error.jsp");
				return false;
			} else {
				return handleInvalidToken(request, response, handler);
			}
		}
		logger.info("通过验证...");
		return true;
	}

	/**
	 * 当出现一个非法令牌时调用
	 */
	protected boolean handleInvalidToken(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		TokenResult tokenResult = new TokenResult();
		tokenResult.setMessage("token验证失败");
		tokenResult.setStatus("999");
		writeMessageUtf8(response, tokenResult);
		return false;
	}

	private void writeMessageUtf8(HttpServletResponse response, TokenResult tokenResult) throws IOException {
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json");
		//response.setContentType("text/html;charset=UTF-8");
		try {
			response.getWriter().print(JsonUtils.toJson(tokenResult));
		} finally {
			response.getWriter().close();
		}
	}

	protected boolean isRedirectMethod(HttpServletRequest request, HttpServletResponse response,
			HandlerMethod handlerMethod) {
		Method method = handlerMethod.getMethod();
		Class<?> returnType = method.getReturnType();
		if (returnType.getClass().equals(Void.class)) {
			return true;
		}
		if (ModelAndView.class.isAssignableFrom(returnType)) {
			return true;
		}
		if (!method.isAnnotationPresent(ResponseBody.class)) {
			return true;
		}
		return false;
	}

}
